import sys
from PyQt5 import QtGui, QtCore
from PyQt5.QtCore import QThread, pyqtSignal, QWaitCondition, QMutex
from PySide2.QtUiTools import QUiLoader
from PyQt5.QtWidgets import QApplication, QMessageBox, QTableWidgetItem, QFileDialog, QMainWindow
from GetHostIP import HostIP
import socket
from time import localtime


class Stats:
    def __init__(self):
        # 从文件中加载UI定义
        # 从 UI 定义中动态 创建一个相应的窗口对象
        # 注意：里面的控件对象也成为窗口对象的属性了
        # 比如 self.ui.button , self.ui.textEdit
        # http://www.b520.cc/2_2157/
        self.ui = QUiLoader().load('ui/appui3.ui')
        ip = HostIP().ip
        self.HPortStatus = 0
        self.DIPStatus = 0
        self.DPortStatus = 0

        self.udpSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        self.ui.setWindowTitle("网络调试助手")
        self.ui.pushButton_2.setEnabled(False)  # 发送
        # self.ui.pushButton_3.setEnabled(False)  # 连接
        self.ui.pushButton_4.setEnabled(False)  # 保存
        self.ui.pushButton_3.clicked.connect(self.establishConnection)
        self.ui.pushButton_2.clicked.connect(self.sendData)
        self.ui.pushButton.clicked.connect(self.clearTextBrowser)
        self.ui.pushButton_5.clicked.connect(self.clearLineText)
        self.ui.pushButton_4.clicked.connect(self.saveLog)
        self.ui.comboBox_2.addItem(ip)
        self.ui.lineEdit_6.setText('4433')

    def clearTextBrowser(self):
        self.ui.textBrowser.clear()

    def clearLineText(self):
        self.ui.lineEdit_5.clear()

    def infoCompleted(self):
        self.isDestPort()
        self.isDestIP()
        if self.DPortStatus * self.DIPStatus == 1:
            return True
        return False

    def establishConnection(self):
        if self.infoCompleted():
            self.ui.pushButton_4.setEnabled(True)
            self.ui.textBrowser.append("OK")
            self.ui.pushButton_2.setEnabled(True)
            self.threadRecv.start()

    def saveLog(self):
        mainWindow = QMainWindow()
        msgBox = QMessageBox()
        filePath = QFileDialog.getSaveFileName(mainWindow, u'选择要保存的位置', './log.txt', '*')[0]
        log = str(self.ui.textBrowser.toPlainText())
        with open(filePath, "a") as f:
            f.write(log)
        QMessageBox.information(msgBox, '提示', '保存成功!')

    def isDestPort(self):
        dest_port = self.ui.lineEdit_3.text()
        if dest_port is not None and dest_port != '':
            self.DPortStatus = 1

    def isDestIP(self):
        dest_ip = self.ui.lineEdit_4.text()
        if dest_ip is not None and dest_ip != '':
            self.DIPStatus = 1

    def recvData(self, info):
        t = localtime()
        tStr = str(t.tm_hour) + ':' + str(t.tm_min) + ':' + str(t.tm_sec)
        info = eval(info)
        addr = str(info[0]).replace('(', '[').replace(')', ']')
        data = info[1]
        self.ui.textBrowser.append(addr + '\t' + tStr)
        self.ui.textBrowser.append('>>' + data + '\n')

    def sendData(self):
        data = self.ui.lineEdit_5.text()
        dest_ip = self.ui.lineEdit_4.text()
        dest_port = int(self.ui.lineEdit_3.text())
        self.udpSocket.sendto(data.encode("gb2312"), (dest_ip, dest_port))


class MyThread(QThread):
    valueChangeSignal = pyqtSignal(str)

    def __init__(self, *args, **kwargs):
        super(MyThread, self).__init__(*args, **kwargs)
        self._isPause = False

        self.cond = QWaitCondition()
        self.mutex = QMutex()

    def pause(self):
        print("线程休眠")
        self._isPause = True

    def resume(self):
        print("线程启动")
        self._isPause = False
        self.cond.wakeAll()

    def run(self):
        while True:
            self.mutex.lock()
            if self._isPause:
                self.cond.wait(self.mutex)
            self.valueChangeSignal.emit(self._value)
            self.mutex.unlock()


if __name__ == '__main__':
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts)
    app = QApplication(sys.argv)
    stats = Stats()
    stats.ui.show()
    app.exec_()
